<script>
import { cloneDeep, random } from "lodash";
import { mapGetters, mapActions } from "vuex";
import { LayoutModel, CustomDrag, CustomConfig, areasConfig, layoutConfig } from "./components";
export default {
  name: "Ai-Pass",
  components: {
    LayoutModel,
    CustomDrag,
    CustomConfig,
  },
  data() {
    return {
      value: "",
      model: 1,
      dragItem: null,
      slots: areasConfig,
      contextData: {},
      // 当前点击（编辑）的组件
      editInfo: {
        editDragId: "",
        slotKey: "",
      },
      dragList: [
        {
          code: "Input",
          name: "输入框",
          icon: "icon-biaodanzujian-shurukuang",
          style: {
            width: "200px",
            // height: "50px",
          },
          props: {
            value: "",
            placeHolderValue: "默认值",

          },
          events: {
            click: "",
            change: ""
          },
          methods: ["query", "delete"],
        },
        {
          code: "Option",
          name: "选择器",
          icon: "icon-biaodanzujian-xialakuang",
          style: {},
          props: {
            data: [
              {
                value: "New York",
                label: "New York",
              },
              {
                value: "London",
                label: "London",
              },
              {
                value: "Sydney",
                label: "Sydney",
              },
              {
                value: "Ottawa",
                label: "Ottawa",
              },
              {
                value: "Paris",
                label: "Paris",
              },
              {
                value: "Canberra",
                label: "Canberra",
              },
            ],
            value: "",
          },
        },
        {
          code: "Button",
          name: "按钮",
          icon: "icon-gongyezujian-kaiguan",
          style: {
            width: "100px",
            // height: "50px",
          },
          props: {
            value: "",
            type: "error",
            ghost: true,
          },
        },
        {
          code: "Table",
          name: "表格2",
          icon: "icon-biaodanzujian-biaoge",
          style: {
            width: "100%",
            height: "100%",
          },
          props: {
            columns: [
              {
                title: "Name",
                key: "name",
              },
              {
                title: "Age",
                key: "age",
              },
              {
                title: "Address",
                key: "address",
              },
            ],
            data: [
              {
                name: "John Brown",
                age: 18,
                address: "New York No. 1 Lake Park",
                date: "2016-10-03",
              },
              {
                name: "Jim Green",
                age: 24,
                address: "London No. 1 Lake Park",
                date: "2016-10-01",
              },
              {
                name: "Joe Black",
                age: 30,
                address: "Sydney No. 1 Lake Park",
                date: "2016-10-02",
              },
              {
                name: "Jon Snow",
                age: 26,
                address: "Ottawa No. 2 Lake Park",
                date: "2016-10-04",
              },
            ],
          },
        },
      ],
    };
  },
  computed: {
    ...mapGetters({
      layoutType: "layout/layoutType",
      layoutConfigs: "layout/layoutConfigs",
    }),
  },
  watch: {
    model: {
      handler(val) {
        console.log(val);
        this.setLayoutType(val);
      },
    },
    layoutConfigs: {
      handler(val) {
        console.log(val);
        const root = document.querySelector(":root");
        let attributes = "";
        // 挂载颜色
        Object.keys(val).map((key) => {
          attributes += `--${key}:${val[key]};`;
        });
        root.setAttribute("style", `${attributes}`);
      },
      immediate: true,
      deep: true,
    },
  },
  created() {
    this.slots.forEach((key) => {
      this.contextData[key] = {};
      // 布局样式
      this.contextData[key]["style"] = layoutConfig[key];
      // 拖拽节点
      this.contextData[key]["data"] = [];
    });

    this.contextData = cloneDeep(this.contextData);

    // 监听是否点击 画布外面
    // window.addEventListener("mousedown", (e) => {
    //   const clickEl = e.target;
    //   console.log(this.$refs.modelContent);
    //   if (this.$refs.modelContent.contains(clickEl)) {
    //     console.log("点击画布内部");
    //   } else {
    //     console.log("点击画布外部");
    //     this.editInfo = this.$options.data().editInfo;
    //   }
    // });
  },
  methods: {
    ...mapActions({
      setLayoutType: "layout/setLayoutType",
    }),
    dragstart(e, item) {
      this.dragItem = item;
      // 设置元素的放置行为——移动
      this.$refs.modelContent.addEventListener("dragenter", this.dragenter);
      // 在目标元素经过 必须要阻止默认行为 否则不能触发drop
      this.$refs.modelContent.addEventListener("dragover", this.dragover);
      // 离开目标元素时设置元素的放置行为——不能拖放
      this.$refs.modelContent.addEventListener("dragleave", this.dragleave);
      // 拖动元素在目标元素松手时添加元素到画布
      this.$refs.modelContent.addEventListener("drop", this.drop);
    },
    dragend() {
      this.$refs.modelContent.removeEventListener("dragenter", this.dragenter);
      this.$refs.modelContent.removeEventListener("dragover", this.dragover);
      this.$refs.modelContent.removeEventListener("dragleave", this.dragleave);
      this.$refs.modelContent.removeEventListener("drop", this.drop);
    },
    dragenter(e) {
      e.dataTransfer.dropEffect = "move";
      console.log("进入", e);
      if (e.target.className == "custom-drag") {
        e.target.style.border = "3px dotted #19be6b";
      }
    },
    dragover(e) {
      e.preventDefault();
    },
    dragleave(e) {
      e.dataTransfer.dropEffect = "none";
      console.log("离开", e);
      if (e.target.className == "custom-drag") {
        e.target.style.border = "none";
      }
    },
    drop(e) {
      console.log(e, this.dragItem);

      //获取拖拽到的区域
      const dragType = e.target.getAttribute("drag-type");
      console.log("拖拽到的区域", dragType);
      this.contextData[dragType].data.push({
        position: { x: e.offsetX - 70, y: e.offsetY - 70 },
        zIndex: 1,
        code: this.dragItem.code,
        props: this.dragItem.props,
        style: this.dragItem.style,
        id: Date.parse(new Date()).toString().substr(0, 10) + random(0, 9),
      });
      console.log("总的数据", this.contextData);

      // 清除border
      if (e.target.className == "custom-drag") {
        e.target.style.border = "none";
      }
    },
    // mousedown(e, item) {
    //   this.moveItem = item;
    //   document.addEventListener("mousemove", this.mousemove);
    //   document.addEventListener("mouseup", this.mouseup);
    // },
    // mousemove(e) {
    //   const _this = this;
    //   let { clientX, clientY } = e;
    //   const moveIdx = _.findIndex(this.list2, function (o) {
    //     return o.id === _this.moveItem.id;
    //   });
    //   let newList2 = _.cloneDeep(this.list2);
    //   newList2[moveIdx].top = clientY;
    //   newList2[moveIdx].left = clientX;
    //   this.list2 = newList2;
    // },
    // mouseup(e) {
    //   document.removeEventListener("mousemove", this.mousemove);
    //   document.removeEventListener("mouseup", this.mouseup);
    // },
    onClickDrag({ dragItem, slotKey }) {
      console.log(dragItem);
      this.editInfo.editDragId = dragItem.id;
      this.editInfo.slotKey = slotKey;
    },
    onDeleteComp(slotKey, deleteId) {
      this.contextData[slotKey].data = this.contextData[slotKey].data.filter(
        (v) => v.id != deleteId
      );
    },
  },
};
</script>
<template>
  <div class="ai-pass">
    <div>
      <div
        class="drag-item"
        @dragstart="(e) => dragstart(e, item)"
        @dragend="dragend"
        v-for="item in dragList"
        :key="item.code"
        :draggable="true"
      >
        <div :class="['iconfont', `${item.icon}`]"></div>
        <span>{{ item.name }}</span>
      </div>
    </div>
    <div ref="modelContent">
      <LayoutModel>
        <template v-slot:[slotKey] v-for="slotKey in slots">
          <CustomDrag
            @onClickDrag="onClickDrag"
            @onDeleteComp="onDeleteComp"
            :areaData.sync="contextData[slotKey]"
            :slotKey="slotKey"
            :key="slotKey"
            :editDragId="editInfo.editDragId"
          />
        </template>
      </LayoutModel>
    </div>
    <div class="change-layout">
      <RadioGroup size="small" v-model="model" :vertical="true" type="button" button-style="solid">
        <Radio :label="1">单页面</Radio>
        <Radio :label="2">上下页面</Radio>
        <Radio :label="3">左右页面</Radio>
        <Radio :label="4">PC页面</Radio>
      </RadioGroup>
    </div>
    <div class="config">
      <!-- config -->
      <CustomConfig :config="contextData" :editInfo="editInfo" />
    </div>
  </div>
</template>

<style lang="scss">
// ::-webkit-scrollbar {
//   display: none !important;
// }
</style>
<style lang="scss" scoped>
$primaryColor: #0091ff;

$leftWidth: 320px;
.ai-pass {
  //   padding: 10px;
  height: calc(100vh);
  display: grid;
  grid-template-columns: $leftWidth 1fr $leftWidth;
  gap: 1px;
  background-color: #fff;
  & > div:nth-child(1) {
    width: $leftWidth;
    // display: flex;
    // justify-content: flex-start;
    // align-content: flex-start;
    // flex-wrap: wrap;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: 100px;
    background-color: #242e42;

    .drag-item {
      height: 90px;
      margin: 10px;
      cursor: move;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 5px;
      border-radius: 5px;
      div {
        font-size: 35px;
        color: $primaryColor;
      }
      span {
        color: #fff;
      }
      &:hover {
        background-color: $primaryColor;
        color: #fff;
        div {
          color: #fff;
        }
      }
    }
  }
  & > div:nth-child(2) {
    flex: 1;
  }
  .config {
    background-color: #242e42;
    z-index: 999;
  }
  .change-layout {
    position: fixed;
    bottom: 10px;
    width: $leftWidth;
    text-align: center;
  }

  ::v-deep {
    .drag-item_container {
      cursor: move;
      font-size: "12px";
    }
    .active-item {
    }
    .dragable-container {
      height: 100%;
      border: none;
      cursor: default;
      background-color: #242e42;
    }
    .draggable .handle {
      //   width: 7px;
      //   height: 7px;
      background: none;
      border: 1px solid $primaryColor;
      border-radius: 50%;
    }
    .dragable-container .active {
      border: 1px dashed $primaryColor;
    }
  }
}
</style>
